package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWoker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWoker redisIdWoker;


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redisConfig;

    private BlockingQueue<VoucherOrder> orderQueue = new ArrayBlockingQueue<>(1024 * 1024);

    //创建线程池
    private final static ExecutorService SECKILL_ORDER_SERVICE = Executors.newSingleThreadExecutor();


    private static final DefaultRedisScript<Long> LUA_SECKILL_SCRIPT;

    static {
        LUA_SECKILL_SCRIPT = new DefaultRedisScript<>();
        LUA_SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        LUA_SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 线程提交
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_SERVICE.submit(new VocherOrderHandler());
    }

    /**
     * 使用线程获取消息队列的消息
     */
    private class VocherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //获取消息  XREADGROUP group g1 c1 count 1 block 2000 streams stream.order >
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2L)),
                            StreamOffset.create("stream.order", ReadOffset.lastConsumed())
                    );
                    //获取消息是否成功
                    if (read == null || read.isEmpty()) {
                        //如果有消息失败  说明获取消息失败 ，下次重新获取
                        continue;
                    }
                    MapRecord<String, Object, Object> entries = read.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //如果获取成功，进行创建订单
                    hanlerVocherOrder(voucherOrder);
                    //确认ACK  XACK S1 G1 ID
                    stringRedisTemplate.opsForStream().acknowledge("stream.order", "g1", entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    //获取消息  XREADGROUP group g1 c1 count 1 block 2000 streams stream.order 0
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.order", ReadOffset.from("0"))
                    );
                    //获取消息是否成功
                    if (read == null || read.isEmpty()) {
                        //PendingList没有异常数据 说明没有数据停止循环
                        break;
                    }
                    MapRecord<String, Object, Object> entries = read.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //如果获取成功，进行创建订单
                    hanlerVocherOrder(voucherOrder);
                    //确认ACK  XACK S1 G1 ID
                    stringRedisTemplate.opsForStream().acknowledge("stream.order", "g1", entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }


//    private BlockingQueue<VoucherOrder> orderQueue = new ArrayBlockingQueue<>(1024 * 1024);
//    /**
//     * 线程执行任务
//     */
//    private class VocherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    //1、获取订单队列的订单信息
//                    VoucherOrder voucherOrder = orderQueue.take();
//                    //2、创建订单
//                    hanlerVocherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("订单异常");
//                }
//            }
//        }
//    }

    //代理对象变成成员变量进行方法赋值
    private IVoucherOrderService voucherOrderService_Proxy;

    /**
     * @param voucherOrder
     * @return
     * @apiNote 该方法主要是完成队列订单处理
     */
    private void hanlerVocherOrder(VoucherOrder voucherOrder) {
        //1、创建用户Id
        Long userId = voucherOrder.getUserId();
        //2、创建锁对象
        RLock lock = redisConfig.getLock("lock:order:" + userId);
        //3、获取锁
        boolean isLock = lock.tryLock();
        //4、判断是否获取数据
        if (!isLock) {
            log.error("不允许重复下单");
            return;
        }
        try {
            voucherOrderService_Proxy.creatVocherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 使用redis stream队列
     *
     * @param
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1、执行LUA脚本
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWoker.nextId("order");
        //如果抢购成功，将优惠券id和用户id封装后存入阻塞队列
        Long step = stringRedisTemplate.execute(
                LUA_SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        //2、判断返回结果 如果不等于0则进行判断
        int intStep = step.intValue();
        if (intStep != 0) {
            return Result.fail(intStep == 1 ? "库存不足" : "不能重复下单");
        }
        //获取代理对象
        voucherOrderService_Proxy = (IVoucherOrderService) AopContext.currentProxy();
        //4、返回ID
        return Result.ok(orderId);
    }


    /**
     * 如果抢购成功，将优惠券id和用户id封装后存入阻塞队列
     *
     * @param
     * @return
     */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1、执行LUA脚本
//        Long userId = UserHolder.getUser().getId();
//        //如果抢购成功，将优惠券id和用户id封装后存入阻塞队列
//        Long step = stringRedisTemplate.execute(
//                LUA_SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(), userId.toString()
//        );
//        //2、判断返回结果 如果不等于0则进行判断
//        int intStep = step.intValue();
//        if (intStep != 0) {
//            return Result.fail(intStep == 1 ? "库存不足" : "不能重复下单");
//        }
//        long orderId = redisIdWoker.nextId("order");
//        //3、 获取id存放队列
//        //3.1、创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //3.2创建订单ID
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        //3.3购买的代金券id
//        voucherOrder.setVoucherId(voucherId);
//        //3.4将对象存放到队列中
//        orderQueue.add(voucherOrder);
//        //获取代理对象
//        voucherOrderService_Proxy = (IVoucherOrderService) AopContext.currentProxy();
//        //4、返回ID
//        return Result.ok(orderId);
//    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1、查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2、查询秒杀开始时间
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀还未开始");
//        }
//
//        //3、查询秒杀结束时间
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束");
//        }
//        //4、查询库存是否充足
//        if (voucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
////        //创建用户Id
//        Long userId = UserHolder.getUser().getId();
////        //spring的事务是通过代理对象实现的，如果使用当前类调用，事务不会生效，在开启这个的时候需要引入报aspectjweaver和EnableAspectJAutoProxy配置true暴露代理对象
////        synchronized (userId.toString().intern()) {
////            IVoucherOrderService voucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
////            return voucherOrderService.creatVocherOrder(voucherId);
////        }
//        //自定义锁
////        SimpleRedisLock lock = new SimpleRedisLock("orderId:" + userId, stringRedisTemplate);
//        RedissonClient redissonClient = redisConfig.redissonClient();
//        RLock lock = redissonClient.getLock("lock:orderId:" + userId);
//
//        boolean isLock = lock.tryLock();
//        if (!isLock) {
//            return Result.fail("一人只能购买一次");
//        }
//        try {
//            IVoucherOrderService voucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
//            return voucherOrderService.creatVocherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//    }
    @Override
    @Transactional
    public void creatVocherOrder(VoucherOrder voucherOrder) {
        //1、创建用户Id
        Long userId = voucherOrder.getUserId();
        //2、判断查询用户是否在订单表存在，如果大于0说明不是一人一户 直接返回
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.error("不能重复下单");
            return;
        }
        //3、扣减库存
        boolean success = seckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0).update();
        //4、扣减失败返回报错
        if (!success) {
            log.error("库存不足");
            return;
        }
        //5、创建订单
        save(voucherOrder);
    }
}
